/*
 * CS_REQUEST_BUY_ITEM.cpp
 *
 *  Created on: 2013. 5. 28.
 *      Author: the2
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../NResource/Static.h"

namespace ProjectZ { namespace NCommand {

void Command::CS_REQUEST_BUY_ITEM(User * pUser, ::Network::Packet * pPacket)
{
/*	ZNO_CS_REQUEST_BUY_ITEM					0x230C
	{
		u8	tid;
		str	strproduct_key;
		u8	u8current_slot;
		u8	u8char_class;
		u32	u32level;
	}

	ZNO_SC_REQUEST_BUY_ITEM					0x230D
	{
		s16	s16ack;
		u32	u32buy_seq;
	}*/

	PREPARE_PACKET;

	uint8_t tid				= 0;
	int8_t currentSlot		= 0;
	int8_t classType		= 0;
	int level				= 0;
	Toolkit::Str<128> productKey;

	*pPacket >> tid >> productKey >> currentSlot >> classType >> level;

	DEBUGLOG("CS_REQUEST_BUY_ITEM : tid=%d, product[%s]", tid, productKey.c_str());

	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();

	NResource::ProductData::Flyweight * pFly = NResource::Static::InstancePtr()->GetProductResource()->GetFly(pUser, tid);

	if (NULL == pFly)
	{
		DEBUGLOG("CS_REQUEST_BUY_ITEM : pFly is NULL!!");
		*pAck << static_cast<int16_t>(ACK_UNKNOWN_ERROR);
		*pAck << static_cast<int>(-1);
		pAck->MakePacket(CMD_SC_REQUEST_BUY_ITEM);
		pUser->Send(pAck);
		return;
	}

	std::string lvStage = std::to_string(pUser->GetCharacterInfo().level);

	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::S_PROCEDURE);
	clsAuto->MakeQuery("call sp_insert_BuyItemData('%s','%s','%s',%d,'%s',%d,%d,'%s',%d,%d,'%s',%d,'%s','%s',%d,%d)",
				pUser->Getuuid().c_str(),
				"",		// PHONE_NUMBER
				"",		// DEVICE ID
				pUser->GetUserSeq(),
				pUser->GetSocialID().c_str(),
				pUser->GetCompany(),
				pUser->GetSaleCode(),
				"",		// PHONE_MODEL
				tid,	// PRODUCT TID
				0,		// RECV_USER_SEQ
				"",		// APP_VER
				pUser->GetCharacterInfo().slotindex,
				lvStage.c_str(),	// LEVEL
				"",		// ORDER_ID
				pFly->_PRICE,
				REQUESTING);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
	{
		DEBUGLOG("CS_REQUEST_BUY_ITEM : false == ::Database::GETSESSION()->SyncExecute(1, clsAuto)");
		*pAck << static_cast<int16_t>(ACK_DB_ERROR);
		*pAck << static_cast<int>(-1);
		pAck->MakePacket(CMD_SC_REQUEST_BUY_ITEM);
		pUser->Send(pAck);
		return;
	}

	if( clsAuto->GetErrorIdx() != 0 )
	{
		DEBUGLOG("CS_REQUEST_BUY_ITEM : clsAuto->GetErrorIdx() != 0");
		*pAck << static_cast<int16_t>(ACK_DB_ERROR);
		*pAck << static_cast<int>(-1);
		pAck->MakePacket(CMD_SC_REQUEST_BUY_ITEM);
		pUser->Send(pAck);
		return;
	}

	int buySeq	= 0;
	while( clsAuto->Next() )
		clsAuto->GetRecord() >> buySeq;

	*pAck << static_cast<int16_t>(ACK_OK);
	*pAck << static_cast<int>(buySeq);
	pAck->MakePacket(CMD_SC_REQUEST_BUY_ITEM);
	pUser->Send(pAck);
}

} /*NCommand*/ } /*ProjectZ*/
